

//
//  ZVideoViewController.m
//  ZQLearn
//
//  Created by macfeel on 2019/4/19.
//  Copyright © 2019 macfeel. All rights reserved.
//
#import "MemberViewController.h"
#import "ZVideoViewController.h"
#import "VideoHeadView.h"
#import "BookDetialTableViewCell.h"
#import "PayModel.h"
////*************************播放器相关
#import <ZFPlayer/ZFAVPlayerManager.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import "UIImageView+ZFCache.h"
#import "ZFUtilities.h"
@interface ZVideoViewController ()<UITableViewDelegate,UITableViewDataSource,ZFActionSheetDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)VideoHeadView *headView;

///视频播放相关
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) UIImageView *containerView;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) UIButton *playBtn;

@property (nonatomic,strong)UIImageView *bofangImg;
@property (nonatomic,strong)UIImageView *coverImg;

@property(nonatomic,copy)NSString *payStatus;
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *orderId;

@end
#define cellIdentifier @"bookdetail"

@implementation ZVideoViewController
-(UITableView *)tableView{
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 0, ScreenWidth , ScreenHeight - kTabHeight-ScreenHeightFlex-52) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 70;
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"BookDetialTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        
        //        WeakStament(ws);
        //        _tableView.mj_header = [CustomRefreshHeader headerWithRefreshingBlock:^{
        //            [ws refreshData];
        //        }];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
        
    }
    return _tableView;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self.navigationItem setItemWithTitle:@"视频详情" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    
    [self addNavgationRightButtonWithFrame:CGRectMake(0, 0, 35, 35) title:@"收藏" Image:@"" selectedIMG:@"" tartget:self action:@selector(collect)];
    [self.view addSubview:self.tableView];
    
    VideoHeadView *head = [[[NSBundle mainBundle]loadNibNamed:@"VideoHeadView" owner:self options:nil]lastObject];
    [head.buyBtn addTarget:self action:@selector(buyAction) forControlEvents:UIControlEventTouchUpInside];
    [head.openMemBtn addTarget:self action:@selector(openAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.tableHeaderView = head;
    
    self.headView = head;
    
    [self CheckpayStatus];
    
    ////播放器
    [self ConfigVideo];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBofang:)];
    //    [head.bofangImg addGestureRecognizer:tap];
    [self.bofangImg addGestureRecognizer:tap];
    // Do any additional setup after loading the view from its nib.
}

///收藏
-(void)collect{
    
    ///type 1资讯  2视频  3图书    classType 1资讯  2课内  3课外
    //addType   1添加  2删除
    NSDictionary *dict = @{@"type":@"2",@"classType":@"3",@"userInfo.id":[UserInfoSave shareInstance].uid?:@"",@"collectionId":self.MModel.ID?:@"",@"addType":@"1"};
    [ZNetworkService postRequestWithBaseUrl:kCollectUrl setParameters:dict success:^(id result) {
        
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            [AFToast showText:@"收藏成功"];
        }else{
            [AFToast showText:@"已收藏过"];
        }
        
    } fail:^(NSError *error) {
        
    } delegater:nil];
    
}

///判断购买状态
-(void)CheckpayStatus{
    
    if ([self.MModel.price integerValue]==0) {
        
        return;
    }
    NSDictionary *dic = @{@"buyRecordsId":self.MModel.ID?:@"",@"userInfo.id":[UserInfoSave shareInstance].uid?:@""};
    [ZNetworkService postRequestWithBaseUrl:kPayStatusUrl setParameters:dic success:^(id result) {
        //        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            NSString *paymentStatus = result[@"paymentStatus"];
            self.payStatus = paymentStatus;
            YYLog(@"%@",self.payStatus);
        }
        
    } fail:^(NSError *error) {
        
    } delegater:nil];
}

///开通会员
-(void)openAction{
    MemberViewController *mem = [MemberViewController new];
    [self.navigationController pushViewController:mem animated:YES];
}
///点击购买按钮
-(void)buyAction{
    
    //先生成订单和书籍一样的
    [self addOrderOfSource];
    
}

///添加资源订单
-(void)addOrderOfSource{
    
    ///buyRecordsType   1电子书  2视频
    //buyRecordsName  购买的名称
    
    NSDictionary *dict = @{@"videoInfo.discount":@"1",@"videoInfo.price":self.MModel.price?:@"",@"userInfo.id":[UserInfoSave shareInstance].uid?:@"",@"videoInfo.id": self.MModel.ID?:@"",@"buyRecordsType":@"2",@"buyRecordsName":self.name?:@"",};
    
    [ZNetworkService postRequestWithBaseUrl:kAddSourceOrderUrl setParameters:dict success:^(id result) {
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            NSString *orderId = result[@"result"][@"id"];
            self.orderId = orderId;
            ZFActionSheet *sheet = [ZFActionSheet actionSheetWithTitle:nil confirms:@[@"微信支付",] cancel:@"取消" style:ZFActionSheetStyleDefault];
            sheet.delegate = self;
            [sheet show];
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
}
#pragma mark - ZFActionSheet delegate
-(void)clickAction:(ZFActionSheet *)actionSheet atIndex:(NSUInteger)index{
    if (index==0) {
        //微信支付
        //type  1 商城里的商品  2 vip   3 图书视频等资源
        //paytype 1支付宝  2微信
        ///type 1商城商品  2vip  3电子书资源   注意修改type
        NSDictionary *dict = @{@"id":self.orderId?:@"",@"type":@"3",@"paytype":@"2",};
        [ZNetworkService postRequestWithBaseUrl:kCallPayUrl setParameters:dict success:^(id result) {
            YYLog(@"%@",result);
            if ([result[@"errorCode"]integerValue]==0) {
                NSDictionary *ddic = result[@"result"];
                PayModel *model = [PayModel mj_objectWithKeyValues:ddic];
                [PayModel  wxPay:model];
            }else{
                [AFToast showText:@"接口返回错误"];
            }
        } fail:^(NSError *error) {
            
        } delegater:nil];
    }else{
        ///支付宝
        
    }
}
///点击播放按钮
- (void)tapBofang:(UITapGestureRecognizer *)tap
{
    NSString *price = self.MModel.price;
    if ([[UserModel shareInstance].isVip integerValue]==1) {
        [self playVideo];
    }else{
        if ([price integerValue]==0) {
            //价钱为空
            [self playVideo];
        }else{

            if ([self.payStatus isEqualToString:@"1"]) {
                ///已购买
                [self playVideo];
            }else{
                //未购买
                [AFToast showText:@"请先购买视频后再观后"];
            }
        }
    }
}

///播放视频
-(void)playVideo{
    
    self.coverImg.hidden = YES;
    self.bofangImg.hidden = YES;
    ////把这个链接给的时机晚点就可以了c
    NSString *vUrl = self.MModel.videoUrl;
    YYLog(@"%@",vUrl);
    NSString *encodedString = [vUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.player.assetURL = [NSURL URLWithString:encodedString];
    [self.player playTheIndex:0];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.coverImg.hidden = false;
    self.bofangImg.hidden = false;
    
    if (self.MModel) {
        
        self.headView.titleLab.text = self.MModel.name?:@"";
        self.name = self.MModel.name?:@"";
        [self.coverImg sd_setImageWithURL:[NSURL URLWithString:self.MModel.picUrl] placeholderImage:nil];
    }
    self.player.viewControllerDisappear = NO;
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    ///购买按钮隐藏逻辑
    NSString *price = self.MModel.price;
    if ([[UserModel shareInstance].isVip integerValue]==1) {
        
        self.headView.buyBtn.hidden = YES;
        self.headView.openMemBtn.hidden = YES;
        
    }else{
        
        if ([price integerValue]==0) {
            //价钱为空
            self.headView.buyBtn.hidden = YES;
            
        }else{
            //价钱不为空再看是否购买了
            //            self.headView.twoyuanGouBtn.hidden = false;
            if ([self.payStatus isEqualToString:@"1"]) {
                
                self.headView.buyBtn.hidden = YES;
                
            }else{
                
                self.headView.buyBtn.hidden = NO;
                
            }
        }
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    self.player.viewControllerDisappear = YES;
    ///这一步很关键，不然播放器停不掉
    [self.player stop];
    
}

#pragma mark - datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //视频
    BookDetialTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    //        NewsModel *model = self.dataArray[indexPath.row];
    //        [videoCell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kPicServerUrl,model.photo]] placeholderImage:nil];
    //        videoCell.titleLab.text = model.title;
    return cell;
}

#pragma delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - 视频播放器相关

static NSString *kVideoCover = @"https://upload-images.jianshu.io/upload_images/635942-14593722fe3f0695.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240";

-(void)ConfigVideo{
    
    self.containerView.frame = CGRectMake(0, 0, ScreenWidth, 210);
    [self.tableView addSubview:self.containerView];
    
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 210)];
    img.image = WDImgName(@"中考");
    self.coverImg = img;
    [self.tableView addSubview:img];
    
    UIImageView *bofangImg = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-35, 80, 45, 45)];
    bofangImg.image = WDImgName(@"bofang");
    bofangImg.userInteractionEnabled = YES;
    self.bofangImg = bofangImg;
    [self.tableView addSubview:bofangImg];
    
    //    [self.containerView addSubview:self.playBtn];
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    /// 播放器相关
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.containerView];
    self.player.controlView = self.controlView;
    
    ///关闭自动播放
    self.player.shouldAutoPlay = false;
    /// 设置退到后台继续播放
    self.player.pauseWhenAppResignActive = NO;
    WeakStament(ws);
    //    @weakify(self)
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        //        @strongify(self)
        [ws setNeedsStatusBarAppearanceUpdate];
    };
    
    /// 播放完成
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        //        @strongify(self)
        [ws.player.currentPlayerManager replay];
        [ws.player playTheNext];
        if (!ws.player.isLastAssetURL) {
            
            //            NSString *title = [NSString stringWithFormat:@"视频标题%zd",ws.player.currentPlayIndex];
            
            //            [ws.controlView showTitle:title coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeLandscape];
        } else {
            [ws.player stop];
        }
    };
    
    self.player.customAudioSession = YES;
    self.player.playerReadyToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:nil];
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
    };
    
}


- (void)playClick:(UIButton *)sender {
    
    //    [self.player playTheIndex:0];
    ///可以设置视频标题
    //    [self.controlView showTitle:@"" coverURLString:kVideoCover fullScreenMode:ZFFullScreenModeAutomatic];
    
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.player.isFullScreen) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    /// 如果只是支持iOS9+ 那直接return NO即可，这里为了适配iOS8
    return self.player.isStatusBarHidden;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

- (BOOL)shouldAutorotate {
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
        _controlView.autoHiddenTimeInterval = 3;
        _controlView.autoFadeTimeInterval = 0.5;
        //        _controlView.coverImageView.image = WDImgName(@"我的背景");
        
    }
    return _controlView;
}

- (UIImageView *)containerView {
    if (!_containerView) {
        _containerView = [UIImageView new];
        [_containerView setImageWithURLString:@"" placeholder:[ZFUtilities imageWithColor:[UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1] size:CGSizeMake(1, 1)]];
    }
    return _containerView;
}

- (UIButton *)playBtn {
    if (!_playBtn) {
        _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playBtn setImage:[UIImage imageNamed:@"new_allPlay_44x44_"] forState:UIControlStateNormal];
        //        [_playBtn addTarget:self action:@selector(playClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playBtn;
}




@end
